import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_luban/flutter_luban.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/io.dart';

/// 上传图片组件
/// 功能包括 选择方式 压缩 上传
class UploadImg {
  /// 选择图片
  static pick(BuildContext context, Function(String) callback) async {
    return await showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          title: Text("选择图片"),
          message: Text("选择以下选项获取图片"),
          cancelButton: CupertinoActionSheetAction(
            onPressed: () => Navigator.pop(context),
            child: Text("取消"),
          ),
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () async {
                File image = await ImagePicker.pickImage(source: ImageSource.camera);
                if (image == null) {
                  Navigator.pop(context);
                  return;
                } else {
                  Navigator.pop(context, 1);
                }
                // File file = await compressPhoto(image);
                String url = await chockimage(image);
                if (url == null) return;
                callback(url);
              },
              child: Text("相机"),
            ),
            CupertinoActionSheetAction(
              onPressed: () async {
                File image = await ImagePicker.pickImage(source: ImageSource.gallery);
                if (image == null) {
                  Navigator.pop(context);
                  return;
                } else {
                  Navigator.pop(context, 2);
                }
                // File file = await compressPhoto(image);
                String url = await chockimage(image);
                if (url == null) return;
                callback(url);
              },
              child: Text("系统相册"),
            ),
          ],
        );
      },
    );
  }

  /// 压缩图片
  static Future<File> compressPhoto(File file) async {
    List<String> sl = file.toString().split('/');
    sl..remove('File: \'')..removeLast();
    String dir = '/';
    int i = 1;
    sl.forEach((str) {
      if (i < sl.length) {
        dir += str+'/';
      } else {
        dir += str;
      }
      i++;
    });

    CompressObject compressObject = CompressObject(
      imageFile: file,
      path: dir,
    );
    String _path = await Luban.compressImage(compressObject);
    return File(_path);
  }

  /// 上传图片
  static Future<String> chockimage(img) async {
    Response res = await Io.updateFile('vedio/upload', img, size: '51200000');
    if (res.data['status'] == 1) {
      return res.data['data'];
    } else {
      showToast(res.data['msg']);
      return null;
    }
  }
}
